//
//  54_螺旋矩阵.swift
//  Swift-LeetCode
//
//  Created by 卢悦明 on 2024/3/15.
/**
 https://leetcode.cn/problems/spiral-matrix/description/
 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 输出：[1,2,3,6,9,8,7,4,5]
 
 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
 输出：[1,2,3,4,8,12,11,10,9,5,6,7]

 */

import UIKit

class LouXuan: NSObject {
    
    func QA() {
        print(spiralOrder([[1,2,3],[4,5,6],[7,8,9]]));
        print(spiralOrder([[1,2,3,4],[5,6,7,8],[9,10,11,12]]));

    }
    
    func spiralOrder(_ matrix: [[Int]]) -> [Int] {
        if matrix.count == 0 {
            return []
        }
        var array = [Int]()
        var top = 0
        var left = 0
        var bottom = matrix.count -  1
        var right = matrix[0].count - 1
        while left <= right && top <= bottom {
            // top: 从左到右
            for i in left...right {
                array.append(matrix[top][i])
            }
            top += 1
            if top > bottom { break }
            
            // right: 从上到下
            for i in top...bottom {
                array.append(matrix[i][right])
            }
            right -= 1
            if left > right { break }

            // bottom: 从右到左
            for i in (left...right).reversed() {
                array.append(matrix[bottom][i])
            }
            bottom -= 1
            if top > bottom { break }

            // left: 从下到上
            for i in (top...bottom).reversed() {
                array.append(matrix[i][left])
            }
            left += 1
            if left > right { break }

        }
        return array
    }
}
